from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection
from apps.verifications import constants
from utils.response_code import RETCODE
class ImageCodeView(View):
    def get(self,request,uuid):
        #1.接收前端的UUID 唯一标示符
        #2.生成图片验证码---第三方包captach
        from libs.captcha.captcha import captcha
        text,image_code=captcha.generate_captcha()

        #3.保存redis数据库（1.配置redis库2.django_redis)
        from django_redis import get_redis_connection
        img_redis_client=get_redis_connection("verify_image_code")
        # img_redis_client.setex("img_%s"%uuid,300,text)
        from . import constants
        img_redis_client.setex("img_%s"%uuid,constants.IMAGE_CODE_REDIS_EXPIRES,text)
        #4.返回给前端，图片的二进制流
        return http.HttpResponse(image_code,content_type="image/jpeg")
class SmsCodeView(View):
    def get(self,request,mobile):
        #1.接收3个mobile;图片验证验证码img_code;uuid==image_code_id
        image_code=request.GET.get("image_code")
        uuid=request.GET.get('image_code_id')

        #2.验证码img_code和redis存储的验证码 是否一致（1.redis取出来（4步）2.判断是否相等3.redis img_code 删除）
        #2.1 链接redis
        img_redis_client=get_redis_connection("verify_image_code")
        #2.2取出来 key=uuid
        redis_img_code=img_redis_client.get("img_%s"%uuid)
        if redis_img_code is None:
            return http.JsonResponse({"code":"4001","errmsg":"验证码失效了"})
        #2.3判断
        #千万注意redis取出来类型 是bytes.decode()
        if image_code.lower()!=redis_img_code.decode().lower():
            return http.JsonResponse({"code":"4001","errmsg":"输入图形验证码有误"})
        #2.4删除redis里面image_code
        img_redis_client.delete("img_%s"%uuid)
        #3.生成随机6位 短信验证码内容 random.randit()
        from random import randint
        sms_code="%06d"%randint(0,999999)
        #4.存储 随机6位 redis里面（3步）
        sms_redis_client=get_redis_connection("sms_code")
        #从redis中取出 避免频繁发送短信的标识
        send_flag=sms_redis_client.get("send_flag_%s"%mobile)
        #判断 如果标识存在，不能再次发送
        if send_flag:
            return http.JsonResponse({"code":RETCODE.THROTTLINGERR,"errmsg":"发送短信过于频繁"})
        #如果不存在，短信发送，标识倒计时再次开启
        p1=sms_redis_client.pipeline()
        p1.setex("send_flag_%s"%mobile,60,1)
        p1.setex("sms_%s"%mobile,constants.IMAGE_CODE_REDIS_EXPIRES,sms_code)
        p1.execute()

        #发短信--第三方容量云
        # from libs.yuntongxun.sms import CCP
        #手机号，验证码，过期时间，短信模板1
        # CCP().send_template_sms(mobile,[sms_code,5],1)
        # CCP().send_template_sms(mobile,[sms_code,constants.SMS_CODE_EXPIRES],1)
        # print("短信验证码是：%s"%sms_code)
        #发短信--第三方容量云
        from celery_tasks.sms.tasks import cpp_send_sms_code
        cpp_send_sms_code.delay(mobile,sms_code)
        #返回响应对象
        return http.JsonResponse({"code":"0","errmsg":"发送短信成功"})

